package com.yuhong.springbootinit.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yuhong.springbootinit.model.entity.*;
import com.yuhong.springbootinit.service.*;
import com.yuhong.springbootinit.common.BaseResponse;
import com.yuhong.springbootinit.common.DeleteRequest;
import com.yuhong.springbootinit.common.ErrorCode;
import com.yuhong.springbootinit.common.ResultUtils;
import com.yuhong.springbootinit.constant.CommonConstant;
import com.yuhong.springbootinit.exception.BusinessException;
import com.yuhong.springbootinit.exception.ThrowUtils;
import com.yuhong.springbootinit.model.dto.application.ApplicationAddRequest;
import com.yuhong.springbootinit.model.dto.application.ApplicationEditRequest;
import com.yuhong.springbootinit.model.dto.application.ApplicationQueryRequest;
import com.yuhong.springbootinit.model.dto.application.ApplicationUpdateRequest;

import com.yuhong.springbootinit.model.enums.ApplicationStatusEnum;
import com.yuhong.springbootinit.model.enums.InvitationStatusEnum;
import com.yuhong.springbootinit.model.vo.ApplicationVO;

import com.yuhong.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.yuhong.springbootinit.model.enums.UserRoleEnum.HR;

@RestController
@RequestMapping("/application")
@Slf4j
public class ApplicationController {

    @Resource
    private UserService userService;

    @Resource
    private ApplicationService applicationService;

    @Resource
    private CompanyPositionService companyPositionService;

    @Resource
    private PositionService positionService;

    @Resource
    private CompanyUserService companyUserService;

    @Resource
    private ProfileService profileService;

    /**
     * 创建
     *
     * @param applicationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addApplication(@RequestBody ApplicationAddRequest applicationAddRequest, HttpServletRequest request) {
        if (applicationAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //页面中有上传简历的提示 上传好简历之后返回一个简历id， 再把简历id放到添加职位申请的请求中

        Application application = new Application();
        BeanUtils.copyProperties(applicationAddRequest, application);

        applicationService.validApplication(application, true);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUserAccount,applicationAddRequest.getUserId());
        User user = userService.getOne(queryWrapper);

        application.setUserId(user.getUserAccount());
        application.setUserName(user.getUserName());
        application.setStatus(InvitationStatusEnum.PUBLISHED.getCode());

        boolean result = applicationService.save(application);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newApplicationId = application.getId();
        return ResultUtils.success(newApplicationId);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteApplication(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUserAccount,deleteRequest.getUserId());
        User user = userService.getOne(queryWrapper);
        long id = deleteRequest.getId();
        // 判断是否存在
        Application oldApplication = applicationService.getById(id);
        ThrowUtils.throwIf(oldApplication == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldApplication.getUserId().equals(user.getUserAccount()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = applicationService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param applicationUpdateRequest
     * @return
     */
    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateApplicationStatus(@RequestBody ApplicationUpdateRequest applicationUpdateRequest) {
        if (applicationUpdateRequest == null || applicationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Application application = new Application();
        BeanUtils.copyProperties(applicationUpdateRequest, application);

        // 参数校验
        if(applicationUpdateRequest.getStatus() == null){
            throw new RuntimeException("参数为空");
        }
        long id = applicationUpdateRequest.getId();
        // 判断是否存在
        Application oldApplication = applicationService.getById(id);
        ThrowUtils.throwIf(oldApplication == null, ErrorCode.NOT_FOUND_ERROR);
        oldApplication.setStatus(application.getStatus());
        boolean result = applicationService.updateById(oldApplication);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ApplicationVO> getApplicationVOById(long id, HttpServletRequest request) throws JsonProcessingException {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Application application = applicationService.getById(id);
        if (application == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(applicationService.getApplicationVO(application, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param applicationQueryRequest
     * @return
     */
    @PostMapping("/list/page")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Application>> listApplicationByPage(@RequestBody ApplicationQueryRequest applicationQueryRequest) {
        long current = applicationQueryRequest.getCurrent();
        long size = applicationQueryRequest.getPageSize();
        Page<Application> postPage = applicationService.page(new Page<>(current, size),
                applicationService.getQueryWrapper(applicationQueryRequest));
        return ResultUtils.success(postPage);
    }

    /**
     * 分页获取当前公司的申请列表（封装类）
     *
     * @param applicationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/company/list/page/vo")
    public BaseResponse<Page<ApplicationVO>> listApplicationVOByPage(@RequestBody ApplicationQueryRequest applicationQueryRequest,
                                                             HttpServletRequest request) {
        long current = applicationQueryRequest.getCurrent();
        long size = applicationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        //获取当前用户所在的公司 userId为当前登录用户的userAccount
        CompanyUser companyInfoByUserId = companyUserService.getCompanyInfoByUserId(applicationQueryRequest.getUserId());
        String companyId = companyInfoByUserId.getCompanyId();
        applicationQueryRequest.setCompanyId(companyId);

        Page<Application> applicationPage = applicationService.page(new Page<>(current, size),
                applicationService.getQueryWrapper(applicationQueryRequest));
        return ResultUtils.success(applicationService.getApplicationVOPage(applicationPage, request));
    }

    /**
     * 分页获取当前用户创建的申请列表
     *
     * @param applicationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ApplicationVO>> listMyApplicationVOByPage(@RequestBody ApplicationQueryRequest applicationQueryRequest,
                                                               HttpServletRequest request) {
        if (applicationQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        applicationQueryRequest.setUserAccount(applicationQueryRequest.getUserAccount());
        long current = applicationQueryRequest.getCurrent();
        long size = applicationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Application> applicationPage = applicationService.page(new Page<>(current, size),
                applicationService.getQueryWrapper(applicationQueryRequest));

        Page<ApplicationVO> applicationVOPage = applicationService.getApplicationVOPage(applicationPage, request);

        return ResultUtils.success(applicationVOPage);
    }


    /**
     * 分页获取当前hr用户创建的职位的申请列表
     *
     * @param applicationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/hr/list/page/vo")
    public BaseResponse<Page<ApplicationVO>> listMyHrApplicationVOByPage(@RequestBody ApplicationQueryRequest applicationQueryRequest,
                                                                       HttpServletRequest request) {
        if (applicationQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        QueryWrapper<User> queryWrapper0 = new QueryWrapper<>();
        queryWrapper0.lambda().eq(User::getUserAccount,applicationQueryRequest.getUserId());
        User user = userService.getOne(queryWrapper0);
        if(!HR.getValue().equals(user.getUserRole()) ){
            throw new RuntimeException("操作人权限不合法");
        }

        //查询当前登录用户的创建的职位
        QueryWrapper<Position> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(Position::getUserId, applicationQueryRequest.getUserId());
        List<Position> positionList = positionService.list(queryWrapper1);
        List<String> positionIds = positionList.stream().map(Position::getPositionId).collect(Collectors.toList());

        //根据职位id查询对应的职位是否有申请
        QueryWrapper<Application> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().in(Application::getPositionId, positionIds);
        //再拼接其他条件
        String positionId = applicationQueryRequest.getPositionId();
        String companyId = applicationQueryRequest.getCompanyId();
        String userAccount = applicationQueryRequest.getUserAccount();
        Integer status = applicationQueryRequest.getStatus();
        String sortField = applicationQueryRequest.getSortField();
        String sortOrder = applicationQueryRequest.getSortOrder();
        long current = applicationQueryRequest.getCurrent();
        long size = applicationQueryRequest.getPageSize();

        queryWrapper2.eq(ObjectUtils.isNotEmpty(positionId), "position_id", positionId);
        queryWrapper2.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper2.ne("status", ApplicationStatusEnum.REJECTED.getCode());
        queryWrapper2.ne("status", ApplicationStatusEnum.ACCEPTED.getCode());
        queryWrapper2.ne("status", ApplicationStatusEnum.INTERVIEW.getCode());
        queryWrapper2.eq(ObjectUtils.isNotEmpty(companyId), "company_id", companyId);
        queryWrapper2.eq(ObjectUtils.isNotEmpty(userAccount), "user_id", userAccount);
        queryWrapper2.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);

        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Application> applicationPage = applicationService.page(new Page<>(current, size), queryWrapper2);
        Page<ApplicationVO> applicationVOPage = applicationService.getApplicationVOPage(applicationPage, request);

        for(ApplicationVO applicationVO : applicationVOPage.getRecords()){
            String profileId = applicationVO.getProfileId();
            Profile profile = profileService.getProfileByProfileId(profileId);
            if(profile == null){
                continue;
            }
            applicationVO.setLocation(profile.getLocation());
            applicationVO.setBg(profile.getBg());
            applicationVO.setGen(profile.getGen());

        }

        return ResultUtils.success(applicationVOPage);

    }

    // endregion

    /**
     * 编辑（用户） 只能修改简历
     *
     * @param applicationEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editApplication(@RequestBody ApplicationEditRequest applicationEditRequest, HttpServletRequest request) {
        if (applicationEditRequest == null || applicationEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Application application = new Application();
        BeanUtils.copyProperties(applicationEditRequest, application);

        // 参数校验
        if(StrUtil.isBlank(applicationEditRequest.getProfileId())){
            throw new RuntimeException("参数为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUserAccount,applicationEditRequest.getUserId());
        User loginUser = userService.getOne(queryWrapper);

        long id = applicationEditRequest.getId();
        // 判断是否存在
        Application oldApplication = applicationService.getById(id);
        ThrowUtils.throwIf(oldApplication == null, ErrorCode.NOT_FOUND_ERROR);

        oldApplication.setProfileId(applicationEditRequest.getProfileId());

        // 仅本人或管理员可编辑
        if (!oldApplication.getUserId().equals(loginUser.getUserAccount()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = applicationService.updateById(oldApplication);
        return ResultUtils.success(result);
    }
}
